$(document).ready(function() {
    // IndexedDB初始化
    let db;
    const dbName = 'UserDB';
    const dbVersion = 1;
    
    // 登录相关变量
    const $captchaInput = $('#captcha');
    const $captchaImage = $('#captchaImage');
    const $refreshBtn = $('.refresh-btn');
    const $loginBtn = $('#loginBtn');
    const $loginForm = $('#loginForm');
    const $registerForm = $('#registerForm');

    let currentCaptcha = '';
    let isVerified = false;
    let autoRefreshTimer;

    // 初始化数据库
    initDatabase();
    
    // 初始化事件绑定
    initEventHandlers();

    function initDatabase() {
        const request = indexedDB.open(dbName, dbVersion);
        
        request.onerror = function(event) {
            console.error('数据库错误：', event.target.error);
        };
        
        request.onsuccess = function(event) {
            db = event.target.result;
            console.log('数据库连接成功');
            window.userDB = db;
            // 数据库连接成功后初始化验证码
            refreshCaptcha();
        };
        
        request.onupgradeneeded = function(event) {
            db = event.target.result;
            if (!db.objectStoreNames.contains('users')) {
                const store = db.createObjectStore('users', { keyPath: 'username' });
                store.createIndex('email', 'email', { unique: true });
                console.log('用户表创建成功');
            }
        };
    }

    function initEventHandlers() {
        console.log('初始化事件绑定');
        
        // 切换表单显示
        $('.switch-btn').on('click', function() {
            console.log('切换按钮点击');
            const formType = $(this).data('form');
            $('.switch-btn').removeClass('active');
            $(this).addClass('active');
            
            if (formType === 'login') {
                $loginForm.fadeIn(300).addClass('form-active');
                $registerForm.fadeOut(300).removeClass('form-active');
                refreshCaptcha();
            } else {
                $registerForm.fadeIn(300).addClass('form-active');
                $loginForm.fadeOut(300).removeClass('form-active');
                if (typeof initRegisterForm === 'function') {
                    initRegisterForm();
                }
            }
        });

        // 登录表单提交
        $loginForm.on('submit', function(e) {
            console.log('登录表单提交');
            e.preventDefault();
            if (!isVerified) {
                alert('请输入正确的验证码！');
                return;
            }
            
            const username = $('#username').val();
            const password = $('#password').val();
            
            if (!username || !password) {
                alert('请输入账号和密码！');
                return;
            }

            // 验证用户登录信息
            const transaction = db.transaction(['users'], 'readonly');
            const store = transaction.objectStore('users');
            const request = store.get(username);

            request.onsuccess = function(event) {
                const user = event.target.result;
                if (user && user.password === password) {
                    alert('登录成功！');
                    if (autoRefreshTimer) {
                        clearInterval(autoRefreshTimer);
                    }
                } else {
                    alert('账号或密码错误！');
                    $('#password').val('');
                    refreshCaptcha();
                }
            };
        });

        // 验证码输入验证
        $captchaInput.on('input', function() {
            console.log('验证码输入');
            const input = $(this).val().toUpperCase();
            $(this).removeClass('valid invalid');
            
            if(input.length === 4) {
                if(input === currentCaptcha) {
                    isVerified = true;
                    $loginBtn.prop('disabled', false).addClass('active');
                    $(this).addClass('valid');
                } else {
                    isVerified = false;
                    $loginBtn.prop('disabled', true).removeClass('active');
                    $(this).addClass('invalid');
                    setTimeout(() => {
                        refreshCaptcha();
                    }, 500);
                }
            } else {
                isVerified = false;
                $loginBtn.prop('disabled', true).removeClass('active');
                $(this).removeClass('valid invalid');
            }
        });

        // 刷新验证码按钮点击事件
        $refreshBtn.on('click', function() {
            console.log('刷新验证码按钮点击');
            if (!$(this).hasClass('refreshing')) {
                refreshCaptcha();
            }
        });

        // 验证码图片点击事件
        $captchaImage.on('click', function() {
            console.log('验证码图片点击');
            refreshCaptcha();
        });
    }

    // 生成验证码
    function generateCaptcha() {
        const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        let captcha = '';
        for(let i = 0; i < 4; i++) {
            captcha += chars[Math.floor(Math.random() * chars.length)];
        }
        return captcha;
    }

    // 刷新验证码
    function refreshCaptcha() {
        console.log('刷新验证码');
        if ($refreshBtn.hasClass('refreshing')) return;

        $refreshBtn.addClass('refreshing');
        
        currentCaptcha = generateCaptcha();
        console.log('新验证码：', currentCaptcha);
        
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = 140;
        canvas.height = 46;

        // 绘制验证码
        drawCaptcha(ctx, currentCaptcha);

        $captchaImage.fadeOut(100, function() {
            $(this).attr('src', canvas.toDataURL('image/png'))
                   .fadeIn(100);
        });
        
        $captchaInput.val('').focus();
        isVerified = false;
        $loginBtn.prop('disabled', true).removeClass('active');

        setTimeout(() => {
            $refreshBtn.removeClass('refreshing');
        }, 500);
    }

    // 绘制验证码
    function drawCaptcha(ctx, code) {
        // 绘制背景
        ctx.fillStyle = '#f8f9fa';
        ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);

        // 绘制文字
        ctx.font = 'bold 24px Arial';
        ctx.textBaseline = 'middle';
        
        for(let i = 0; i < code.length; i++) {
            ctx.fillStyle = `rgb(${Math.random()*150},${Math.random()*150},${Math.random()*150})`;
            ctx.save();
            ctx.translate(25 + i * 30, ctx.canvas.height/2);
            ctx.rotate((Math.random() - 0.5) * 0.4);
            ctx.fillText(code[i], 0, 0);
            ctx.restore();
        }

        // 绘制干扰线
        for(let i = 0; i < 4; i++) {
            ctx.beginPath();
            ctx.strokeStyle = `rgba(${Math.random()*150},${Math.random()*150},${Math.random()*150},0.5)`;
            ctx.moveTo(Math.random() * ctx.canvas.width, Math.random() * ctx.canvas.height);
            ctx.lineTo(Math.random() * ctx.canvas.width, Math.random() * ctx.canvas.height);
            ctx.stroke();
        }
    }

    // 页面卸载时清理定时器
    $(window).on('unload', function() {
        if (autoRefreshTimer) {
            clearInterval(autoRefreshTimer);
        }
    });
}); 